# Code Splitting

<EpicVideo url="https://www.epicreact.dev/workshops/react-performance/intro-to-code-splitting" />

Code splitting acts on the principle that loading less code will speed up your
app. Say for example that we're building a complex dashboard application that
includes the venerable d3 library for graphing data. Your users start
complaining because it takes too long to load the login screen.

So, considering that performance problems can be resolved by less code, how can we
solve this one? Well, do we really _need_ to have that code for the chart when
the user loads the login screen? Nope! We could load that on-demand.

Luckily for us, there's a built-in way to do this with JavaScript standards.
It's called a dynamic import and the syntax looks like this:

```tsx
import('/some-module.js').then(
	(module) => {
		// do stuff with the module's exports
	},
	(error) => {
		// there was some error loading the module...
	},
)
```

> 📜 Learn more about dynamic imports in the browser in
> [Super Simple Start to ESModules in the browser](https://kentcdodds.com/blog/super-simple-start-to-es-modules-in-the-browser)

To take this further, React has built-in support for loading modules as React
components. The module must have a React component as the default export, and
you have to use the `<Suspense />` component to render a fallback value while
the user waits for the module to be loaded.

```tsx
// smiley-face.tsx
export default function SmileyFace() {
	return <div>😃</div>
}

// app.tsx
import { lazy, Suspense } from 'react'

const SmileyFace = lazy(() => import('./smiley-face.tsx'))

function App() {
	return (
		<div>
			<Suspense fallback={<div>loading...</div>}>
				<SmileyFace />
			</Suspense>
		</div>
	)
}
```

🦉 One great way to analyze your app to determine the need/benefit of code
splitting for a certain feature/page/interaction, is to use
[the "Coverage" feature of the developer tools](https://developer.chrome.com/docs/devtools/coverage).
